import { h, onMounted, reactive, ref, toRaw,watch } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  getUserListApi,
  createUserApi,
  updateUserApi,
  delUserApi,
  getUserShowApi,
  getJobTitleListApi,
  getDeptListApi,
  updateUserStatusApi,
  updateUserPassWordApi,
  getUserSelectOptionsApi,
  getRbacRoleListApi
} from "@/api/user";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 10,
    departmentId: "",
    username: "",
    name: "",
    entryDate: "",
    phone: "",
    jobTitleId: "",
    gender: "",
    status: "",
    isSuperAdmin: ""
    
  });
  const genderOptions = ref([
  	{
  		id: 1,
  		name: '男'
  	},
  	{
  		id: 2,
  		name: '女'
  	}
  ])
  const statusOptions = ref([
  	{
  		id: 1,
  		name: '启用'
  	},
  	{
  		id: 2,
  		name: '禁用'
  	}
  ])
  const isSuperAdminOptions = ref([
  	{
  		id: 0,
  		name: '否'
  	},
  	{
  		id: 1,
  		name: '是'
  	}
  ])
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const higherDeptOptions = ref();
  const roleIds = ref()
  const userSelection = ref([])
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const getStatusType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "未审核" : "danger";
      case 1:
        return text ? "启用" : "primary";
      case 2:
        return text ? "禁用" : "info";
    }
  };
  const columns: TableColumnList = [
    {
      label: "用户ID",
      prop: "userId"
    },
    {
      label: "部门ID",
      prop: "departmentId"
    },
    {
      label: "用户名",
      prop: "username"
    },
    // {
    //   label: "密码",
    //   prop: "password"
    // },
    {
      label: "姓名",
      prop: "name",
    },
    {
      label: "入职时间",
      prop: "entryDate",
      minWidth: 100
    },
    {
      label: "电话",
      prop: "phone"
    },
    {
      label: "邮箱",
      prop: "email"
    },
    {
      label: "职位ID",
      prop: "jobTitleId"
    },
    {
      label: "性别",
      prop: "gender",
	  // formatter:(val)=> {
	  // 	return val==1?'男':'女'
	  // },
	  cellRenderer: ({ row, props }) => (
		  <el-tag
			size={props.size}
			type={row.gender === 0 ? "danger" : null}
			effect="plain"
		  >
			{row.gender === 1 ? "男" : "女"}
		  </el-tag>
		)
    },
    {
      label: "状态",
      prop: "status",
	 //  formatter:({ row })=> {
	 //  	return row.status==1?'启动':'禁用'
		
	 //  },
		cellRenderer: scope => (
			<el-switch
			  size={scope.props.size === "small" ? "small" : "default"}
			  v-model={scope.row.status}
			  active-value={1}
			  inactive-value={2}
			  active-text="启用"
			  inactive-text="禁用"
			  inline-prompt
			  onClick={() => switchStatus(scope as any)}
			/>
		)
    },
	// {
	//   label: "备注",
	//   prop: "remarks"
	// },
	{
	  label: "是否为超级管理员",
	  prop: "isSuperAdmin",
	  // formatter:(row)=> {
		 //  console.log(row)
	  // 	return row.isSuperAdmin==1?'是':'否'
	  // },
	  cellRenderer: ({ row, props }) => (
		  <el-tag
			size={props.size}
			type={row.isSuperAdmin === 1 ? null : "danger"}
			effect="plain"
		  >
			{row.isSuperAdmin === 1 ? "是" : "否"}
		  </el-tag>
		)
	},
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 180
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getUserListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getUserListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  function switchStatus ({ row }) {
  	ElMessageBox.confirm(
	  `确认要<strong>${
		row.status === 2 ? "禁用" : "启用"
	  }</strong><strong style='color:var(--el-color-primary)'>${
		row.username
	  }</strong>用户吗?`,
	  "系统提示",
	  {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
		dangerouslyUseHTMLString: true,
		draggable: true
	  }
	)
	  .then(async() => {
		let params = {
			userId: row.userId,
			status: row.status === 2 ? 2 : 1
		}
		await updateUserStatusApi(params);
		onSearch()
		
		message("已成功修改用户状态", {
			type: "success"
		});
	  })
	  .catch(() => {
		row.status === 2 ? (row.status = 1) : (row.status = 2);
	  });
  }
  
  async function onSearch() {
    loading.value = true;
    const { result } = await getUserListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  const jobSelectOptions = ref([])
  async function getJobTitleSelectOptions () {
	 const { result } = await getJobTitleListApi();
	 jobSelectOptions.value = result
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function formatHigherDeptOptions(treeList: any) {
      // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
      if (!treeList || !treeList.length) return;
      const newTreeList = [];
      for (let i = 0; i < treeList.length; i++) {
        treeList[i].disabled = treeList[i].status === 0 ? true : false;
        formatHigherDeptOptions(treeList[i].children);
        newTreeList.push(treeList[i]);
      }
      return newTreeList;
    }
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
		roleIdsOptions: roleIds.value,
      };
    } else {
      const { result } = await getUserShowApi({ userId: row.userId });
      formInline.value = {
        title: "修改",
		higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
		roleIdsOptions: roleIds.value,
		roleIds: row.roleIds,
        userId: result?.id ?? "",
        departmentId: result?.departmentId ?? "",
        username: result?.username ?? "",
        password: result?.password ?? "",
        name: result?.name ?? "",
        entryDate: result?.entryDate ?? "",
        phone: result?.phone ?? "",
        email: result?.email ?? "",
        jobTitleId: result?.jobTitleId ?? "",
        gender: result?.gender ?? "",
        status: result?.status ?? "",
        remarks: result?.remarks ?? "",
        isSuperAdmin: result?.isSuperAdmin ?? "",
        
        
      };
	  
    }
    addDialog({
      title: `${title}用户信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了工作计划`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createUserApi(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateUserApi(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  // 用户选项
  async function getUserSelect() {
	  const { result } = await getUserSelectOptionsApi();
	  userSelection.value = result
  }
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
	{ color: "#e74242", text: "非常弱" },
	{ color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();

  const ruleFormRef = ref()
  /** 重置密码 */
    function handleResetPwd(row: any) {
      addDialog({
        title: `重置 ${row.username} 用户的密码`,
        width: "30%",
        draggable: true,
        closeOnClickModal: false,
        fullscreen: deviceDetection(),
        contentRenderer: () => (
          <>
            <ElForm ref={ruleFormRef} model={pwdForm}>
              <ElFormItem
                prop="newPwd"
                rules={[
                  {
                    required: true,
                    message: "请输入新密码",
                    trigger: "blur"
                  }
                ]}
              >
                <ElInput
                  clearable
                  show-password
                  type="password"
                  v-model={pwdForm.newPwd}
                  placeholder="请输入新密码"
                />
              </ElFormItem>
            </ElForm>
          </>
        ),
        closeCallBack: () => (pwdForm.newPwd = ""),
        beforeSure: done => {
          ruleFormRef.value.validate(async valid => {
            if (valid) {
			  // 表单规则校验通过
			  await updateUserPassWordApi({userId: row?.userId, password: pwdForm.newPwd}) 
              
              message(`已成功重置 ${row.username} 用户的密码`, {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            }
          });
        }
      });
    }
  onMounted(async () => {
    onSearch();
	getJobTitleSelectOptions();
	getUserSelect()
	// 归属部门
	const {result} = await getDeptListApi();
	higherDeptOptions.value = result;
	const data = await getRbacRoleListApi({page:1,perPage: 999});
	roleIds.value = data.result.list
  });

  function handleDelete(row) {
    delUserApi({ userId: row.userId }).then(() => {
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  function confirmStatus() {
    alert("审核通过");
  }
  function refusedStatus() {
    alert("审核拒绝");
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    confirmStatus,
    refusedStatus,
	genderOptions,
	statusOptions,
	isSuperAdminOptions,
	jobSelectOptions,
	handleResetPwd,
	userSelection
  };
}
